<script setup lang="ts">
  import { h, ref, watch, onBeforeMount } from 'vue';
  import { useForm } from '@/hooks/arco/useForm';
  import { useSelectOption } from '@/hooks/arco/useSelectOption';
  import {
    queryInstStations,
    createInstStation,
    updateInstStation,
  } from '@/api/structure-management/station';
  import { Modal, Message } from '@arco-design/web-vue';
  import * as Lodash from 'lodash';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import { fillData } from '@/views/lhj-v1/util';
  import { queryBaseAreaInfo } from '@/api/system';

  const loading = ref(false);
  // 基础信息
  const baseNameMap = {
    btnAddSite: '新增站点',
    btnDelete: '删除',
    btnEdit: '编辑',
    emptyDesc: '暂无站点信息',
    tabTitle: '站点列表',
    tabKeys: {
      id: '站点ID',
      name: '站点名称',
      shortName: '站点简称',
      status: '站点状态',
      area: '所在地区',
      address: '详细地址',
    } as any,
  };

  const drawer = ref({
    visible: false,
    type: '',
    title: '新增站点',
    okText: '保存',
    cancelText: '取消',
  });
  const modalConfig = {
    title: '提示',
    bodyStyle: 'text-align: center;',
  };

  const addForm = useForm({
    state: {
      name: '',
      shortName: '',
      status: 0,
      area: [],
      address: '',
      instId: '',
    },
    rules: {
      name: {
        required: true,
        message: `请输入${baseNameMap.tabKeys.name}`,
      },
      shortName: {
        required: true,
        message: `请输入${baseNameMap.tabKeys.shortName}`,
      },
      status: {
        required: true,
        message: `请选择${baseNameMap.tabKeys.status}`,
      },
      area: {
        required: true,
        message: `请选择站点${baseNameMap.tabKeys.area}`,
      },
      address: {
        required: true,
        message: `请输入站点${baseNameMap.tabKeys.address}`,
      },
    },
  });

  const dataAreas = ref<any>([]);
  const dataPage = ref({
    page: 1,
    pageSize: 1000,
    total: -1,
  });
  // const dataSiteList = ref<any[]>([]);

  const dataCurrentSite = ref<any>({
    id: '',
    name: '',
    shortName: '',
    status: null,
    area: '',
    address: '',
    //
    instId: '',
  });

  // 获取地址(码)
  const getBaseAreaInfo = async () => {
    queryBaseAreaInfo()
      .then((res) => {
        for (let i = 0; i < res.length; i += 1) {
          dataAreas.value = res;
        }
      })
      .catch((err) => {});
  };

  const dataSiteList = useSkeleton({
    apiFun: queryInstStations,
    initQueryParams: [dataPage.value.page, dataPage.value.pageSize],
    onSuccess(data) {
      if (data) {
        dataPage.value.total = data.total;
      }
    },
  });

  const handleClickSite = (item: any) => {
    item.area = '';
    if (item.provinceName) {
      item.area += item.provinceName;
    }
    if (item.cityName) {
      item.area += item.cityName;
    }
    if (item.districtName) {
      item.area += item.districtName;
    }
    fillData(dataCurrentSite.value, item);
    // updateCurrentSite(item);
  };

  const resetCurrentSite = (sites: any[]) => {
    console.log(sites);
    for (let i = 0; i < sites.length; i += 1) {
      const item = sites[i];
      if (item.id === dataCurrentSite.value.id) {
        handleClickSite(item);
      }
    }
  };

  const handleDrawerOk = () => {
    // console.log('area:', addForm.state);
    addForm
      .validate()
      .then(() => {
        loading.value = true;
        let modalContent = '确认新增站点？';
        let messageText = '新增成功！';
        let apiFunc = createInstStation;
        const jsonData: any = Lodash.cloneDeep(addForm.state);
        if (drawer.value.type === 'edit') {
          modalContent = '确认保存站点信息？';
          messageText = '保存成功！';
          apiFunc = updateInstStation;
        } else if (drawer.value.type === 'add') {
          // jsonData.ll = '';
        } else {
          return;
        }
        if (jsonData.area && jsonData.area.length >= 3) {
          const [provinceCode, cityCode, districtCode] = jsonData.area;
          jsonData.provinceCode = provinceCode;
          jsonData.cityCode = cityCode;
          jsonData.districtCode = districtCode;
        }
        Modal.confirm({
          ...modalConfig,
          content: modalContent,
          onOk: (e) => {
            apiFunc(jsonData)
              .then(() => {
                drawer.value.type = '';
                Message.success(messageText);
                // getInstStations();
                dataSiteList.execute().then((res) => {
                  resetCurrentSite(res.list);
                });
              })
              .finally(() => {
                loading.value = false;
              });
          },
          onCancel(e) {
            loading.value = false;
          },
        });
      })
      .catch((err) => {});
  };
  const handleSiteAdd = () => {
    drawer.value.type = 'add';
    addForm.backToInit();
  };
  // 删除站点
  const handleSiteDelete = () => {
    //
  };
  const handleSiteEdit = () => {
    drawer.value.type = 'edit';
    addForm.setFieldsValue({
      ...dataCurrentSite.value,
    });
  };

  onBeforeMount(() => {
    getBaseAreaInfo();
    // getInstStations();
  });

  watch(
    () => drawer.value.type,
    (newVal) => {
      switch (newVal) {
        case 'add': {
          // drawer.value.okText = '保存';
          break;
        }
        case 'edit': {
          drawer.value.title = '编辑站点';
          break;
        }
        default: {
          drawer.value.visible = false;
          loading.value = false;
          return;
        }
      }
      drawer.value.visible = true;
    }
  );
</script>

<template>
  <div
    class="m-station flex"
    :style="{
      height: '100%',
      columnGap: '20px',
    }"
  >
    <div class="flex-col" :style="{ width: '240px' }">
      <a-button style="height: 36px" type="primary" long @click="handleSiteAdd">
        <template #icon><icon-plus /></template>
        <template #default>{{ baseNameMap.btnAddSite }}</template>
      </a-button>
      <div
        :style="{
          marginTop: '4px',
          flex: 1,
          // backgroundColor: 'var(--color-neutral-3)', //'#F2F3F5',
        }"
      >
        <skeleton-view v-slot="{ data }" v-bind="dataSiteList.bindProps">
          <div v-if="data.list.length === 0" :style="{ marginTop: '30%' }">
            <a-empty>
              <template #image>
                <img src="@/assets/images/structure/empty_box@1x.png" alt="" />
              </template>
              <span>{{ baseNameMap.emptyDesc }}</span>
            </a-empty>
          </div>
          <ul v-else class="flex-col" style="row-gap: 6px; margin-top: 10px">
            <li
              v-for="item in data.list"
              :key="item.id"
              class="site-item"
              :class="{ active: dataCurrentSite.id === item.id }"
              @click="handleClickSite(item)"
            >
              <span>{{ item.name }}</span>
            </li>
          </ul>
        </skeleton-view>
      </div>
    </div>
    <a-card hoverable :style="{ flex: 1 }" class="flex-col v-expand-card">
      <a-tabs default-active-key="1" :style="{ height: '100%' }">
        <a-tab-pane key="1" :title="baseNameMap.tabTitle">
          <ul>
            <li
              v-for="(key, index) of Object.keys(baseNameMap.tabKeys)"
              :key="'ik-' + index"
              class="flex"
              :style="{ padding: '10px 0' }"
            >
              <span
                :style="{
                  padding: '0 20px',
                  textAlign: 'right',
                  width: '96px',
                }"
                >{{ baseNameMap.tabKeys[key] }}</span
              >
              <span v-if="!dataCurrentSite[key]">—</span>
              <span v-else>
                <span v-if="key == 'status'">{{
                  dataCurrentSite[key] == 1 ? '正常' : '停用'
                }}</span>
                <span v-else>{{ dataCurrentSite[key] }}</span>
              </span>
            </li>
          </ul>
        </a-tab-pane>
      </a-tabs>
      <template #actions>
        <a-space>
          <!-- :disabled="!dataCurrentSite.id" -->
          <a-button disabled @click="handleSiteDelete">
            <template #icon><icon-delete /></template>
            <template #default>{{ baseNameMap.btnDelete }}</template>
          </a-button>
          <a-button
            type="primary"
            :disabled="!dataCurrentSite.id"
            @click="handleSiteEdit"
          >
            <template #icon><icon-edit /></template>
            <template #default>{{ baseNameMap.btnEdit }}</template>
          </a-button>
        </a-space>
      </template>
    </a-card>
    <div>
      <a-drawer
        :width="380"
        :visible="drawer.visible"
        unmount-on-close
        @cancel="drawer.type = ''"
      >
        <template #title>{{ drawer.title }}</template>
        <a-form v-bind="addForm.bindProps" layout="vertical">
          <a-form-item field="name" required>
            <template #label>
              <span>{{ baseNameMap.tabKeys.name }}</span>
            </template>
            <a-input
              v-model="addForm.state.name"
              :placeholder="'请输入' + baseNameMap.tabKeys.name"
            />
          </a-form-item>
          <a-form-item field="shortName" required>
            <template #label>
              <span>{{ baseNameMap.tabKeys.shortName }}</span>
            </template>
            <a-input
              v-model="addForm.state.shortName"
              :placeholder="'请输入' + baseNameMap.tabKeys.shortName"
            />
          </a-form-item>
          <a-form-item field="status" required>
            <template #label>
              <span>{{ baseNameMap.tabKeys.status }}</span>
            </template>
            <a-select v-model="addForm.state.status">
              <a-option :value="1" label="正常" />
              <a-option :value="0" label="停用" />
            </a-select>
          </a-form-item>
          <a-form-item field="area" required>
            <template #label>
              <span>{{ baseNameMap.tabKeys.area }}</span>
            </template>
            <a-cascader
              v-model="addForm.state.area"
              expand-trigger="hover"
              path-mode
              :options="dataAreas"
              :placeholder="'请选择站点' + baseNameMap.tabKeys.area"
            />
          </a-form-item>
          <a-form-item field="address" required>
            <template #label>
              <span>{{ baseNameMap.tabKeys.address }}</span>
            </template>
            <a-input
              v-model="addForm.state.address"
              :placeholder="'请输入' + baseNameMap.tabKeys.address"
            />
          </a-form-item>
        </a-form>
        <template #footer>
          <a-space>
            <a-button @click="drawer.type = ''">
              <template #icon><icon-close-circle /></template>
              <template #default>{{ drawer.cancelText }}</template>
            </a-button>
            <a-button type="primary" :loading="loading" @click="handleDrawerOk">
              <template #icon><icon-save /></template>
              <template #default>{{ drawer.okText }}</template>
            </a-button>
          </a-space>
        </template>
      </a-drawer>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .m-station {
    .site-item {
      padding: 8px 18px;
      cursor: pointer;
      color: var(--color-text-1);
      border: 1px solid rgb(var(--arcoblue-4));
      border-radius: 6px;

      &:hover {
        background-color: rgb(var(--arcoblue-1));
      }

      &.active {
        background-color: rgb(var(--arcoblue-1));
        color: rgb(var(--primary-6));
      }
    }
  }
</style>
